package 链表;

import java.util.Arrays;

/**
 * @author yzh
 * @version 1.0
 * @date 2021/10/9 9:42
 */
public class CopyList {
    public static void main(String[] args) {
        final Node init = Node.init(Arrays.asList(1, 2, 3, 4, 5));
        System.out.println(init);
        System.out.println(copyList_three(init));
    }

    // 递归
    public static Node copyList(Node head) {
        if (head == null) return null;
        Node node = new Node(head.val);
        node.next = copyList(head.next);
        return node;
    }

    // 迭代
    public static Node copyList_two(Node head) {
        Node newNode = new Node(0);
        for (Node node = newNode; head != null; head = head.next) {
            node.next = new Node(head.val);
            node = node.next;
        }
        return newNode.next;
    }

    // 节点拆分
    public static Node copyList_three(Node head) {
        if (head == null) return head;
        for (Node node = head; node != null; node = node.next.next) {
            Node newNode = new Node(node.val);
            newNode.next = node.next;
            node.next = newNode;
        }
        Node newHead = head.next;
        for (Node node = head; node != null; node = node.next) {
            Node newNode = node.next;
            node.next = newNode.next;
            newNode.next = node.next != null ? node.next.next : null;
        }
        return newHead;
    }

}
